package com.zks.setting;


import cn.hutool.core.lang.Singleton;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.StaticLog;
import com.zks.Filter.Filter;
import com.zks.action.Action;
import com.zks.action.DefaultAction;
import com.zks.action.ErrorAction;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Setting {
    private static final Log log = StaticLog.get();
    /** 默认的字符集编码 */
    public final static String DEFAULT_CHARSET = "utf-8";

    public final static String MAPPING_ALL = "/*";

    public final static String MAPPING_ERROR = "/_error";

    /** 字符编码 */
    private static String charset = DEFAULT_CHARSET;
    /** 端口 */
    private static int port = 8090;

   //filter 列表
    private static Map<String, Filter> filterMap;
    /** Action映射表 */
    private static Map<String, Action> actionMap;

    static{
        filterMap = new ConcurrentHashMap<String, Filter>();

        actionMap = new ConcurrentHashMap<String, Action>();
        actionMap.put(StrUtil.SLASH, new DefaultAction());

        actionMap.put(MAPPING_ERROR, new ErrorAction());

    }


    public static Map<String, Filter> getFilterMap() {
        return filterMap;
    }

    public static int getPort(){
        return port;
    }
    public static void setPort(int port) {
        Setting.port = port;
    }

    /**
     * @return 获取编码
     */
    public static String getCharset() {
        return charset;
    }


    public static Filter getFilter(String path){
        if(StrUtil.isBlank(path)){
            path = StrUtil.SLASH;
        }
        return getFilterMap().get(path.trim());
    }


    /**
    * 获取action
    * @author zks
    * @date 2019/4/14 13:20
    * @return com.zks.action.Action
    */
    public static Action getAction(String path){
        if(StrUtil.isBlank(path)){
            path = StrUtil.SLASH;
        }
        return getActionMap().get(path.trim());
    }

    public static Map<String, Action> getActionMap() {
        return actionMap;
    }


    /**
     * 增加Action类，已有的Action类将被覆盖<br>
     * 所有Action都是以单例模式存在的！
     * @param path 拦截路径（必须以"/"开头）
     * @param actionClass Action类
     */
    public static void setAction(String path, Class<? extends Action> actionClass) {
        setAction(path, (Action) Singleton.get(actionClass));
    }

    /**
     * 设置Action类，已有的Action类将被覆盖
     * @param path 拦截路径（必须以"/"开头）
     * @param action Action类
     */
    public static void setAction(String path, Action action) {
        if(StrUtil.isBlank(path)){
            path = StrUtil.SLASH;
        }

        if(null == action) {
            log.warn("Added blank action, pass it.");
            return;
        }
        //所有路径必须以 "/" 开头，如果没有则补全之
        if(false == path.startsWith(StrUtil.SLASH)) {
            path = StrUtil.SLASH + path;
        }

        Setting.actionMap.put(path, action);
    }

}
